import 'package:flutter/material.dart';
import 'package:flutter_layout/base/index.dart';
import 'package:flutter_layout/main/base_stateful_widget.dart';

import 'package:styled_widget/styled_widget.dart';

// ConstrainedBox：适用于需要设置最大/小宽高，组件大小以来子组件大小，但不能超过设置的界限。
// UnconstrainedBox：用到情况不多，当作ConstrainedBox的子组件可以“突破”ConstrainedBox的限制，超出界限的部分会被截取。
// SizedBox：适用于固定宽高的情况，常用于当作2个组件之间间隙组件。
// AspectRatio：适用于固定宽高比的情况。
// FractionallySizedBox：适用于占父组件百分比的情况。
// LimitedBox：适用于没有父组件约束的情况。
// Container：适用于不仅有尺寸的约束，还有装饰（颜色、边框、等）、内外边距等需求的情况。
class ConstrainPage extends BaseStatefulWidget {
  const ConstrainPage({Key? key}) : super(key: key);

  @override
  _ConstrainPageState createState() => _ConstrainPageState();
}

class _ConstrainPageState extends State<ConstrainPage> {
  int currentIndex = 0;
  PageController pageController = PageController();

  var pageLsit = [
    const CachePage(
      title: "1",
    ),
    const CachePage(
      title: "2",
    ),
    const CachePage(
      title: "3",
    ),
    const CachePage(
      title: "4",
    ),
    const CachePage(
      title: "5",
    ),
    const CachePage(
      title: "6",
    ),
    const CachePage(
      title: "7",
    ),
    const CachePage(
      title: "8",
    )
  ];
  var titleTool = [
    "ConstrainedBox",
    "UnconstrainedBox",
    "SizedBox",
    "AspectRatio",
    "FractionallySizedBox",
    "LimitedBox",
    "Container",
    "Flexible",
  ];
  String? toolTitle;

  @override
  Widget build(BuildContext context) {
    var bottomItem = <BottomNavigationBarItem>[];
    for (var i = 0; i < pageLsit.length; i++) {
      bottomItem.add(BottomNavigationBarItem(icon: const Icon(Icons.access_alarm_rounded), label: "$i"));
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(toolTitle ?? titleTool[0]),
      ),
      body: PageView(
        physics: const PageScrollPhysics(),
        controller: pageController,
        children: pageLsit,
        onPageChanged: (value) {
          currentIndex = value;
          _changeItem(currentIndex);
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        onTap: (value) {
          setState(() {
            currentIndex = value;
            showToast("$currentIndex");
            pageController.jumpToPage(currentIndex);
          });
        },
        type: BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        // backgroundColor: Colors.yellow,
        items: bottomItem,
      ),
    );
  }

  void _changeItem(int value) {
    // pageController.position =1;
    // pageController.page = currentIndex.toDouble();
    setState(() {
      currentIndex = value;
      toolTitle = titleTool[currentIndex];
    });
  }
}

class CachePage extends StatefulWidget {
  final String? title;
  const CachePage({Key? key, this.title}) : super(key: key);

  @override
  _CachePageState createState() => _CachePageState();
}

class _CachePageState extends State<CachePage> with AutomaticKeepAliveClientMixin {
  // String? title;
  // _CachePageState({this.title});
  @override
  Widget build(BuildContext context) {
    super.build(context);
    if ("1" == widget.title) {
      return getConstrainedBox();
    }
    if ("2" == widget.title) {
      return getUnconstrainedBox();
    }
    if ("3" == widget.title) {
      return getSizedBox();
    }
    if ("4" == widget.title) {
      return getAspectRatio();
    }
    if ("5" == widget.title) {
      return getFractionallySizedBox();
    }
    if ("6" == widget.title) {
      return getLimited();
    }
    if ("7" == widget.title) {
      return getContainer();
    }
    return getFlexible();
  }

  // ignore: unused_element
  _getPhysics(String? title) {
    return const BouncingScrollPhysics();
  }

  Column getFlexible() {
    return Column(
      children: <Widget>[
        Flexible(
            flex: 3,
            child: Container(
              color: Colors.red,
            )),
        Flexible(
            flex: 1,
            child: Container(
              color: Colors.green,
            )),
        Flexible(
            flex: 2,
            child: Container(
              color: Colors.blue,
            )),
      ],
    );
  }

  Widget getFractionallySizedBox() {
    return Scaffold(
        body: Container(
      height: 200,
      color: Colors.grey,
      child: Column(
        children: <Widget>[
          Container(
            height: 50,
            color: Colors.red,
          ),
          const Flexible(
            child: FractionallySizedBox(
              heightFactor: .1,
            ),
          ),
          Container(
            height: 50,
            color: Colors.blue,
          ),
        ],
      ),
    )

        // Column(children: [
        //   Container(
        //     height: 200,
        //     width: MediaQuery.of(context).size.width,
        //     color: Colors.pink.shade100,
        //     alignment: Alignment.topLeft,
        //     child: Column(
        //       crossAxisAlignment: CrossAxisAlignment.end,
        //       children: <Widget>[
        //         // FractionallySizedBox(
        //         //   alignment: Alignment.topLeft,
        //         //   widthFactor: .7,
        //         //   child: RaisedButton(
        //         //     onPressed: () {},
        //         //     child: Text('button'),
        //         //   ),
        //         // )
        //         // Flexible(
        //         //   child: FractionallySizedBox(
        //         //     widthFactor: .3,
        //         //     heightFactor: 1,
        //         //     child: Align(
        //         //       child: Container(
        //         //         color: Colors.red,
        //         //       ),
        //         //     ),
        //         //   ),
        //         // ),
        //         // Container(
        //         //   height: 10,
        //         //   color: Colors.blue,
        //         // ),
        //       ],
        //     ),
        //   ),
        // ]),
        );
  }

  Widget getSizedBox() {
    return Scaffold(
        body: SizedBox(
      height: 60,
      width: 200,
      child: ElevatedButton(
        onPressed: () {
          // showToast("111");
        },
        child: const Text('宽度：200，高度：60'),
      ),
    ));
  }

  Widget getConstrainedBox() {
    return Column(
      children: [
        const Text(
          "ConstrainedBox：适用于需要设置最大/小宽高，组件大小以来子组件大小，但不能超过设置的界限。",
          style: TextStyle(color: Colors.amber),
        ),
        ConstrainedBox(
          constraints: const BoxConstraints(maxHeight: 60, maxWidth: 200),
          child: Container(height: 300, width: 300, color: Colors.red),
        ).backgroundColor(Colors.green),
        const SizedBox(
          height: 10,
        ),
        ConstrainedBox(
          constraints: const BoxConstraints(maxHeight: 60, maxWidth: 200),
          child: Container(height: 300, width: MediaQuery.of(context).size.width, color: Colors.red),
        ).backgroundColor(Colors.green),
        const SizedBox(
          height: 10,
        ),
        ConstrainedBox(
          constraints: const BoxConstraints(maxHeight: 60, maxWidth: double.infinity),
          child: Container(height: 300, width: MediaQuery.of(context).size.width, color: Colors.red),
        ).backgroundColor(Colors.green),
        // BoxConstraints.tight(Size(100, 100));
        // BoxConstraints.expand(100,100)
        // BoxConstraints提供了便捷的构建函数，方便开发者调用，如BoxConstraints.tight(Size size)和BoxConstraints.expand()等。
      ],
    );
  }

  Widget getUnconstrainedBox() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        const Text(
            "UnconstrainedBox 没有约束\n\n  注意：黄色区域表示子控件超出父控件的区域了，黄色区域只会在debug模式下存在，在release模式下，只有红色区域。UnconstrainedBox虽然不限制其子控件的大小，但仍然受父控件的约束，超出父控件的区域将会截取。UnconstrainedBox允许设置对齐方式，用法如下："),
        const Divider(
          height: 50,
        ),
        SizedBox(
          height: 100,
          width: 100,
          child: UnconstrainedBox(
            alignment: Alignment.centerLeft,
            child: Container(
              height: 200,
              width: 200,
              color: Colors.red,
            ),
          ),
        ),
      ],
    );
  }

  Widget getAspectRatio() {
    return Scaffold(
        body: Column(
      children: [
        const Text("宽高比: 16/9"),
        AspectRatio(
          // 16:9 = width:height
          aspectRatio: 16 / 9,
          child: Container(color: Colors.red),
        ),
      ],
    ));
  }

  @override
  bool get wantKeepAlive => true;

  ///LimitedBox组件是当不受父组件约束时限制它的尺寸，什么叫不受父组件约束？
  ///就像这篇文章介绍的其他组件，它们都会对子组件约束，没有约束的父组件有ListView、Row、Column等，
  ///如果LimitedBox的父组件受到约束，此时LimitedBox将会不做任何操作，我们可以认为没有这个组件，代码如下：
  ///也就是說第二个Container 不受父组件LimitedBox的约束，所以LimitedBox设置宽高对它无效，所以最终宽高将由第一个Container决定，不设定时这自身的宽高
  Widget getLimited() {
    //  ListView(
    //   children: <Widget>[
    //     LimitedBox(
    //       maxHeight: 20,
    //       child: Container(
    //         width: 20,
    //         color: Colors.green,
    //       ),
    //     ),
    //     LimitedBox(
    //       maxHeight: 100,
    //       child: Container(
    //         color: Colors.red,
    //       ),
    //     ),
    //   ],
    // )
    return Scaffold(
        body: Column(children: [
      const Text(
          "LimitedBox组件是当不受父组件约束时限制它的尺寸，什么叫不受父组件约束？\n就像这篇文章介绍的其他组件，它们都会对子组件约束，没有约束的父组件有ListView、Row、Column等，\n如果LimitedBox的父组件受到约束，此时LimitedBox将会不做任何操作，我们可以认为没有这个组件，代码如下：\n也就是說这里的案例LimitedBox受父组件Container的约束，所以LimitedBox设置宽高无效，所以最终宽高将由第一个Container决定"),
      Container(
          color: Colors.amber,
          height: 50,
          width: 50,
          child: LimitedBox(
            maxHeight: 50, //无效
            maxWidth: 100, //无效
            child: Container(
              color: Colors.green,
              child: const Text("dadf"),
            ),
          )),
    ]));
  }

  Widget getContainer() {
    return Scaffold(
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: <Widget>[
          LimitedBox(
            maxHeight: 20,
            child: Container(
              alignment: Alignment.center,
              child: const Text('老孟，一个有态度的程序员'),
              decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.blue),
            ),
          ),
          const SizedBox(height: 10),
          LimitedBox(
            maxHeight: 20,
            child: Container(
              alignment: Alignment.center,
              child: const Text('老孟，一个有态度的程序员'),
              padding: const EdgeInsets.symmetric(horizontal: 10),
              decoration: const BoxDecoration(
                  shape: BoxShape.rectangle, borderRadius: BorderRadius.all(Radius.circular(20)), color: Colors.blue),
            ),
          ),
          const SizedBox(height: 10),
          LimitedBox(
            maxHeight: 24,
            child: Container(
              alignment: Alignment.center,
              child: const Text('老孟，一个有态度的程序员'),
              padding: const EdgeInsets.symmetric(horizontal: 10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: Colors.blue,
                  width: 2,
                ),
              ),
            ),
          ),
          const SizedBox(height: 10),
          LimitedBox(
            maxHeight: 100,
            child: Container(
              alignment: Alignment.center,
              height: 100,
              width: 100,
              decoration: BoxDecoration(
                image: const DecorationImage(
                  image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
                  fit: BoxFit.cover,
                ),
                border: Border.all(
                  color: Colors.blue,
                  width: 2,
                ),
                borderRadius: BorderRadius.circular(12),
              ),
            ),
          ),
          const SizedBox(height: 10),
          // LimitedBox(
          //   maxHeight: 100,
          UnconstrainedBox(
            child: Container(
              height: 100,
              width: 100,
              decoration: BoxDecoration(
                image: const DecorationImage(
                  image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
                  fit: BoxFit.cover,
                ),
                border: Border.all(
                  color: Colors.blue,
                  width: 2,
                ),
                shape: BoxShape.circle,
              ),
            ),
          ),
          const SizedBox(height: 10),
          // LimitedBox(
          //   maxHeight: 30,
          // child:
          UnconstrainedBox(
            child: Container(
              color: Colors.blue,
              child: const Text(
                '老孟程序',
                style: TextStyle(fontSize: 15),
                textAlign: TextAlign.center,
              ),
              alignment: Alignment.centerLeft,
              constraints: const BoxConstraints.tightForFinite(width: 20, height: 100),
            ),
          ),
          const SizedBox(height: 10),
          UnconstrainedBox(
            child: Container(
              color: Colors.blue,
              child: const Text('老孟，一个有态度的程序员'),
              alignment: Alignment.center,
              height: 30,
              width: 100,
              transform: Matrix4.rotationZ(0.9),
            ),
          ),
        ],
      ),
    );
  }
}
